﻿#region License
/*
Copyright (c) 2011, 2012 André N. Klingsheim
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
 
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.

    * Neither the name of the author nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
*/
#endregion

using System;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Reflection.Emit;
using TransformTool.Transformers.Configurable;

namespace TransformTool.Transformers
{
    public static class TransformerHelper
    {
        static List<BaseTransformer> _transformers;

        public static List<BaseTransformer> GetTransformers()
        {
            if (_transformers != null)
                return _transformers;

            var asm = Assembly.GetExecutingAssembly();

            var nameSpace = MethodBase.GetCurrentMethod().ReflectedType.Namespace;
            var allTypes = asm.GetTypes();

            //select subclasses of BaseTransformer, and create an instance of the class.
            var transformers = (from Type t in allTypes
                                where !t.IsInterface && !t.IsAbstract && typeof(BaseTransformer).IsAssignableFrom(t) && !typeof(IDynamicTransformer).IsAssignableFrom(t)
                                select (BaseTransformer)Activator.CreateInstance(t)).ToArray<BaseTransformer>();

            _transformers = new List<BaseTransformer>(transformers);
            _transformers.AddRange(GetDynamicTransformers());
            _transformers.Sort();
            return _transformers;
        }

        public static BaseTransformer GetTransformerByMenuName(String transformerMenuName)
        {
            return (from BaseTransformer bt in GetTransformers()
                    where bt.NameForMenu.Equals(transformerMenuName)
                    select bt).Single();
        }

        public static BaseTransformer GetNewTransformerInstance(BaseTransformer transformer)
        {
            if (transformer is DynamicCharsetEncodeTransformer || transformer is DynamicCharsetDecodeTransformer)
                return GetNewDynamicCharsetTransformerInstance((IDynamicTransformer)transformer);

            return (BaseTransformer)Activator.CreateInstance(transformer.GetType());
        }

        public static String DefaultTransform(Type t, Object value)
        {
            if (t.Equals(typeof(String)))
                return (String)value;

            if (t.Equals(typeof(Byte[])))
            {
                return (String)new HEXEncodeTransformer().Transform(value);
            }

            return null;
        }

        public static BaseTransformer GetDefaultTransformer(Type t)
        {

            if (t.Equals(typeof(Byte[])))
                return new HEXEncodeTransformer();

            if (t.Equals(typeof(string)))
                return new UTF8EncodeTransformer();

            return null;
        }

        public static BaseTransformer GetReverseTransformer(BaseTransformer bt)
        {
            var baseType = bt.GetType();
            if (baseType.BaseType.Equals(typeof(BaseTransformer)) || baseType.BaseType.Equals(typeof(BaseConfigurableTransformer)))
            {
                return (bt.ReverseTransformer == null ? null : (BaseTransformer)Activator.CreateInstance(bt.ReverseTransformer));
            }

            var cryptoTransformer = bt as SymmetricCryptoConfigurableTransformer;
            if (cryptoTransformer != null)
            {
                var newTransformer = (SymmetricCryptoConfigurableTransformer)Activator.CreateInstance(cryptoTransformer.ReverseTransformer);
                newTransformer.Config = cryptoTransformer.Config.GetReverseTransformerConfig();
                return newTransformer;
            }

            Object[] param = new Object[2];

            if (bt is DynamicCharsetEncodeTransformer)
            {
                Type transformType = ((DynamicCharsetEncodeTransformer)bt).ReverseTransformer;
                param[0] = ((DynamicCharsetEncodeTransformer)bt).CodePage;
                param[1] = bt.GetType();

                return (BaseTransformer)Activator.CreateInstance(transformType, param);
            }
            else if (bt is DynamicCharsetDecodeTransformer)
            {

                Type transformType = ((DynamicCharsetDecodeTransformer)bt).ReverseTransformer;
                param[0] = ((DynamicCharsetDecodeTransformer)bt).CodePage;
                param[1] = bt.GetType();
                return (BaseTransformer)Activator.CreateInstance(transformType, param);
            }
            throw new ApplicationException("Could not get a sensible reverse transformer for " + bt.GetType().FullName);
        }

        private static BaseTransformer GetNewDynamicCharsetTransformerInstance(IDynamicTransformer dynamicCharTransformer)
        {

            Object[] param = new Object[2];
            if (dynamicCharTransformer is DynamicCharsetEncodeTransformer)
            {
                var t = (DynamicCharsetEncodeTransformer)dynamicCharTransformer;
                param[0] = t.CodePage;
                param[1] = t.ReverseTransformer;

            }
            else if (dynamicCharTransformer is DynamicCharsetDecodeTransformer)
            {
                var t = (DynamicCharsetDecodeTransformer)dynamicCharTransformer;
                param[0] = t.CodePage;
                param[1] = t.ReverseTransformer;
            }
            else
            {
                throw new ApplicationException("Expected dynamic character encoding transformer, was presented a " + dynamicCharTransformer.GetType().FullName);
            }

            return (BaseTransformer)Activator.CreateInstance(dynamicCharTransformer.GetType(), param);
        }

        private static List<BaseTransformer> GetDynamicTransformers()
        {
            var encInfo = Encoding.GetEncodings();
            AssemblyName name = new AssemblyName("DynamicCharsetTransformers");
            AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
            ModuleBuilder mb = ab.DefineDynamicModule(name.Name);

            //We've built the assembly on the fly. Now, let's define and instantiate all transformers.
            var transformers = new List<BaseTransformer>();

            foreach (var enc in encInfo)
            {
                Type[] ctorTypes = new[] { typeof(int), typeof(Type) };
                TypeBuilder tb = mb.DefineType(GetDynamicEncoderTypeName(enc.CodePage), TypeAttributes.Public, typeof(DynamicCharsetEncodeTransformer));

                ConstructorInfo baseCtor = typeof(DynamicCharsetEncodeTransformer).GetConstructor(ctorTypes);
                ConstructorBuilder ctorBuilder = tb.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, ctorTypes);

                ILGenerator ctorILGen = ctorBuilder.GetILGenerator();
                ctorILGen.Emit(OpCodes.Ldarg_0);
                ctorILGen.Emit(OpCodes.Ldarg_1);
                ctorILGen.Emit(OpCodes.Ldarg_2);
                ctorILGen.Emit(OpCodes.Call, baseCtor);
                ctorILGen.Emit(OpCodes.Ret);

                var encoderType = tb.CreateType();


                tb = mb.DefineType(GetDynamicDecoderTypeName(enc.CodePage), TypeAttributes.Public, typeof(DynamicCharsetDecodeTransformer));
                baseCtor = typeof(DynamicCharsetDecodeTransformer).GetConstructor(ctorTypes);
                ctorBuilder = tb.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, ctorTypes);

                ctorILGen = ctorBuilder.GetILGenerator();
                ctorILGen.Emit(OpCodes.Ldarg_0);
                ctorILGen.Emit(OpCodes.Ldarg_1);
                ctorILGen.Emit(OpCodes.Ldarg_2);
                ctorILGen.Emit(OpCodes.Call, baseCtor);
                ctorILGen.Emit(OpCodes.Ret);

                var decoderType = tb.CreateType();

                Object[] param = { enc.CodePage, decoderType };
                transformers.Add((BaseTransformer)Activator.CreateInstance(encoderType, param));
                param[1] = encoderType;
                transformers.Add((BaseTransformer)Activator.CreateInstance(decoderType, param));
            }

            transformers.Sort();
            return transformers;

        }

        private static string GetDynamicEncoderTypeName(int codePage)
        {
            return "DynamicCharsetEncoder" + codePage;
        }
        private static string GetDynamicDecoderTypeName(int codePage)
        {
            return "DynamicCharsetDecoder" + codePage;
        }
    }
}
